import store from '@/store/index.js'

var optionCallback = null; // 接收回调函数

export const isLocation = (options) => {
	optionCallback = options;

	uni.authorize({
		scope: 'scope.userLocation',
		success: (res) => {
			// 未授权
			isGetLocation();
		},
		fail: (err) => {
			// 执行失败，弹窗提示是否授权
			uni.getSetting({
				success: (result) => {
					if (!result.authSetting['scope.userLocation']) {
						isOpenAuth()
					}
				}
			});
		}
	})
}

/**
 * 获取当前的地理位置
 */
function isGetLocation() {
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			let tmpLocation = {
				latitude: res.latitude,
				longitude: res.longitude
			}
			uni.setStorage({
				key: 'location',
				data: tmpLocation
			});

			// 定位成功 回调
			if (optionCallback != null) {
				optionCallback(tmpLocation);
			}
		},
		fail: (err) => {
			// 失败 回调
			if (optionCallback != null) {
				optionCallback('fail');
			}
		}
	})
}

function isOpenAuth() {
	uni.showModal({
		content: '由于您还没有允许授权位置，无法定位，请点击确定允许授权',
		success: (res) => {
			if (res.confirm) {
				uni.openSetting({
					success: (result) => {
						if (result.authSetting['scope.userLocation']) {
							// 引导用户授权成功 调用获取位置接口
							isGetLocation();
						} else {
							// console.log('失败')
						}
					}
				});
			} else {
				uni.navigateBack({
					delta: 1
				})
			}
		}
	});
}
